package com.vcom.deploy.upgrade;

import com.vcom.deploy.cmd.CmdThread;
import org.noear.solon.annotation.ServerEndpoint;
import org.noear.solon.core.message.Listener;
import org.noear.solon.core.message.Message;
import org.noear.solon.core.message.Session;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 监听模式
 * 方便做会话的组织和收集，比如做聊天室，做应用推送等。
 */
@ServerEndpoint(path = "/ws/upgrade")
public class UpgradeWebSocketServer implements Listener {

    private Process process;
    private InputStream inputStream;
    private InputStream errorStream;

    @Override
    public void onOpen(Session session) {
        String appCode = session.param("appCode");

        AppEnum app = AppEnum.getAppEnumBy(appCode);
        String cmd = "sh /root/vcom/ddc_update/update_from_149.3.sh /root/vcom/ddc_update/" + app.getScriptParams();
        try {
            String[] params = cmd.split(" ");
            ProcessBuilder pb = new ProcessBuilder(params);
            pb.directory(new File("/root/vcom/ddc_update"));
            process = pb.start();
            int exitValue = process.waitFor();
            // 当返回值为0时表示执行成功
            if (0 != exitValue) {
                System.out.println("call shell failed. error code is :" + exitValue);
            }
            inputStream = process.getInputStream();
            errorStream = process.getErrorStream();
            // 一定要启动新的线程，防止InputStream阻塞处理WebSocket的线程
            CmdThread thread = new CmdThread(inputStream, errorStream, session);
            thread.start();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onMessage(Session session, Message message) {
        session.send(message.bodyAsString());
    }

    @Override
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
        Listener.super.onError(session, error);
    }

    /**
     * WebSocket请求关闭
     */
    public void onClose(Session session) {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (errorStream != null) {
                errorStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (process != null) {
            process.destroy();
        }
        Listener.super.onClose(session);
    }

}
